<?php

namespace Wanecho\FlarumAdnet\Controllers;

use Psr\Http\Server\RequestHandlerInterface;
use Laminas\Diactoros\Response\HtmlResponse;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Flarum\Settings\SettingsRepositoryInterface;
use Laminas\Diactoros\Response\JsonResponse;
use Wanecho\FlarumAdnet\AdslistModel;
use Flarum\User\User;

class AdsCallbackController implements RequestHandlerInterface
{
    protected $settings;

    public function __construct(SettingsRepositoryInterface $settings)
    {
        $this->settings = $settings;
    }

    public function handle(Request $request): Response
    {
        $event = $request->getQueryParams(['adpid', 'platform', 'provider', 'trans_id', 'sign', 'user_id', 'extra']);
        $data = [
            "adpid" => $event["adpid"],
            "platform" => $event["platform"],
            "provider" => $event["provider"],
            "trans_id" => $event["trans_id"],
            "sign" => $event["sign"],
            "user_id" => $event["user_id"],
            "extra" => $event["extra"]
        ];
        // 注意::必须验签请求来源
        $secret = $this->settings->get("flarum.adnet.security");
        $looklimit = $this->settings->get("flarum.adnet.looklimit");
        $trans_id = $event["trans_id"];
        $sign2 = hash("sha256", "$secret:$trans_id");
        if ($event["sign"] !== $sign2) {
            return new  HtmlResponse(null);
        }
        $ads = AdslistModel::firstOrCreate(['trans_id' => $trans_id], $data);
        if ($ads && $ads->isreward != 1) {
            //获取当天查看次数
            $today = new \DateTime('now');
            $nums = AdslistModel::where('user_id', $event["user_id"])->whereDate('created_at', $today->format('Y-m-d'))->count();
            if ($nums % $looklimit == 0) {
                //完成次数上限后 赠送VIP
                $user = User::find($event["user_id"]);
                if (!$user->groups->contains($this->settings->get('wanecho-uservip.group_id'))) {
                    $user->groups()->attach($this->settings->get('wanecho-uservip.group_id'));
                }
                //计算到期时间
                $start_time = $this->getStartDate($user->out_time);
                $end_time   = $this->getEndDate($start_time, 'day');
                //赠送一天VIP
                $user->is_vip = 1;
                $user->out_time = $end_time;
                if ($user->save()) {
                    $ads->isreward = 1;
                    $ads->save();
                }
            }
        }
        return new JsonResponse(["isValid" => true], 200);
    }



    private function getEndDate($startDay, $type, $nums = 1)
    {
        $today = new \DateTime('now'); // 当前日期
        $start = new \DateTime($startDay);
        if ($start > $today) {
            $today = $start;
        }
        switch ($type) {
            case 'day':
                return $today->modify("+{$nums} day");
                break;
            case 'month':
                return $today->modify("+{$nums} month");
                break;
            case 'quarter':
                return $today->modify("+3 month");
                break;
            case 'year':
                return $today->modify("+{$nums} year");
                break;
            default:
                return $today;
                break;
        }
    }

    private function getStartDate($startDay)
    {
        $today = new \DateTime('now'); // 当前日期
        if (empty($startDay)) {
            //为空返回当天
            return $today;
        }
        $start = new \DateTime($startDay);
        if ($start < $today) {
            $start = $today;
        }
        return $start->format('Y-m-d H:i:s');
    }
}
